<template>
  <div class="app-container">

    <!--    <h2 style="text-align: center;">发布新课程</h2>-->

    <el-steps :active="0" finish-status="success" process-status="finish" simple align-center
              style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>

    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">

        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'eduoss/fileoss?host=cover'"
          class="avatar-uploader">
          <img :src="courseInfo.cover">
        </el-upload>

      </el-form-item>

      <!-- 所属分类 联级选择器 -->
      <el-form-item label="课程所属分类">
        <el-cascader
          v-model="subjectIDS"
          placeholder="试试搜索：java"
          expand-trigger="hover"
          :options="subjectList"
          :props="defaultProps"
          :change="changAllSubjectId()"
          filterable>
          <template slot-scope="{ node, data }">
            <span>{{ data.title }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <!-- 课程讲师 -->
      <!-- filterable: 可搜索   -->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          filterable
          placeholder="请选择">
          <el-option
            v-for="item in teacherList"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
        元
        <label class="form-tip"><i class="el-icon-warning"></i> 免费课程请设置为0元</label>

      </el-form-item>

      <el-form-item label="课程教材">
        <el-upload
          :show-file-list="false"
          :on-success="handleMaterialSuccess"
          :before-upload="beforeMaterialUpload"
          :action="BASE_API + 'eduoss/fileoss/course'"
          class="material-uploader">
          <el-button type="primary">上传文件</el-button>
          <div v-if="courseInfo.materialUrl" class="material-preview">
            <a :href="courseInfo.materialUrl" target="_blank">已上传教材</a>
            <el-button type="danger" size="mini" @click="removeMaterial" style="margin-left: 10px;">移除</el-button>
          </div>
        </el-upload>
        <div class="el-upload__tip">支持PDF、Word和图片格式</div>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import course from '@/api/edu/course'
  import teacher from '@/api/edu/teacher'
  import subject from '@/api/edu/subject'
  import Tinymce from '@/components/Tinymce' //富文本组件

  const defaultForm = {
    title: '',
    subjectId: '',
    subjectParentId: '',
    teacherId: '',
    lessonNum: 0,
    description: '',
    cover: '',
    price: 0,
    materialUrl: '',
    cover: process.env.OSS_PATH + '/cover/default.png'
  }
  export default {
    data() {
      return {
        courseInfo: defaultForm,
        saveBtnDisabled: false, // 保存按钮是否禁用
        teacherList: [],// 讲师列表
        subjectList: [],//所有课程分类
        subjectIDS: [],//一级和二级分类ID
        defaultProps: {
          children: 'children',
          label: 'title',
          value: 'id'//要存个id
        },
        BASE_API: process.env.BASE_API,
        tempPlaceholder: ''
      }
    },
    components: { Tinymce },
    created() {
      console.log('info created')
      this.init()
    },
    watch: {
      //监听路由变化
      $route(to, from) {
        console.log('watch $route')
        this.init()
      }
    },
    methods: {
      //1. 跳转到第二步
      saveOrUpdate() {
        if (!this.courseInfo.title) {
          this.$message({
            type: 'error',
            message: '请输入课程名称'
          })
          return false
        }
        if(!this.courseInfo.id){//无id回显 添加
          this.saveCourse()
        }else{
          this.updateCourse()
        }
      },
      //2. 获取所有教师
      initTeacherList() {
        teacher.getList().then(result => {
          this.teacherList = result.data
        })
      },
      //3. 过去所有分类
      initSubjectList() {
        subject.getNestedTreeList().then(result => {
          this.subjectList = result.data
        })
      },
      //4. 将SubjectID赋值
      changAllSubjectId() {
        this.courseInfo.subjectParentId = this.subjectIDS[0]
        this.courseInfo.subjectId = this.subjectIDS[1]
      },
      //5. 上传封面成功调用的方法
      handleAvatarSuccess(res, file) {
        this.courseInfo.cover = res.data.url
      },
      //6. 上传之前调用的方法 约定文件类型
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      //7. 上传教材成功调用的方法
      handleMaterialSuccess(res, file) {
        this.courseInfo.materialUrl = res.data.url
        this.$message.success('教材上传成功')
      },
      //8. 上传教材之前调用的方法 约定文件类型
      beforeMaterialUpload(file) {
        const allowedTypes = [
          'application/pdf',                           // PDF
          'application/msword',                        // Word .doc
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // Word .docx
          'image/jpeg',                                // JPEG
          'image/png',                                 // PNG
          'image/gif'                                  // GIF
        ];
        
        const isAllowedType = allowedTypes.includes(file.type);
        const isLt10M = file.size / 1024 / 1024 < 50;

        if (!isAllowedType) {
          this.$message.error('上传文件只能是 PDF、Word 或图片格式!');
        }
        if (!isLt10M) {
          this.$message.error('上传文件大小不能超过 10MB!');
        }
        return isAllowedType && isLt10M;
      },
      //9. 移除教材
      removeMaterial() {
        this.courseInfo.materialUrl = ''
        this.$message.success('教材已移除')
      },
      //10. 初始化回显数据
      init() {
        this.initSubjectList()//初始化课程分类列表
        this.initTeacherList()//初始化教师列表
        if (this.$route.params && this.$route.params.id) {
          const id = this.$route.params.id
          //根据id获取课程基本信息
          this.fetchCourseInfoById(id)
        } else {
          this.courseInfo = { ...defaultForm }
          this.subjectIDS =[]
        }
      },
      //11. 查询回显信息
      fetchCourseInfoById(id) {
        course.getCourseInfoById(id).then(response => {
          console.log(response.data)
          //回显分类id 匹配联级选择器中的:props value
          this.subjectIDS = [response.data.subjectParentId, response.data.subjectId]
          console.log('subjectIDS', this.subjectIDS)
          this.courseInfo = response.data

        }).catch((response) => {
          this.$message({
            type: 'error',
            message: response.message
          })
        })
      },
      //12. 添加课程
      saveCourse(){
        course.saveCourseInfo(this.courseInfo).then(result => {
          this.$message({
            type: 'success',
            message: '保存课程信息成功'
          })
          // console.log(result)
          this.$router.push({ path: `/course/chapter/${result.data.courseId}` })
        })
      },
      //13. 更新课程
      updateCourse(){
        course.updateCourseInfo(this.courseInfo).then(result => {
          this.$message({
            type: 'success',
            message: '修改课程信息成功'
          })
          // console.log(result)
          this.$router.push({ path: `/course/chapter/${this.courseInfo.id}` })
        })
      }
    }
  }
</script>

<style scoped>
  /*提示样式*/
  .form-tip {
    margin-left: 30px;
    color: #909399;
  }

  /*富文本上传图片样式*/
  .tinymce-container {
    line-height: 29px;
  }
  
  /*教材预览样式*/
  .material-preview {
    margin-top: 10px;
  }
</style>
